package repository

import (
	"gitee.com/w5681688/cart/domian/model"
	"github.com/jinzhu/gorm"
	"github.com/micro/go-micro/v2/errors"
)

type ICartRepository interface {
	InitTable() error
	FindCartById(int64) (*model.Cart, error)
	CreateCart(*model.Cart) (int64, error)
	DeleteCartById(int64) error
	UpdateCart(*model.Cart) error
	FindAll(int64) ([]model.Cart, error)

	ClearCart(int64) error
	IncrNum(int64, int64) error
	DecrNum(int64, int64) error
}

type CartRepository struct {
	mysqlDB *gorm.DB
}

func NewCartRepository(db *gorm.DB) ICartRepository {
	return &CartRepository{mysqlDB: db}
}

func (c *CartRepository) InitTable() error {
	return c.mysqlDB.CreateTable(&model.Cart{}).Error
}

func (c *CartRepository) FindCartById(cartId int64) (*model.Cart, error) {
	cart := &model.Cart{}
	return cart, c.mysqlDB.First(cart, cartId).Error
}

func (c *CartRepository) CreateCart(cart *model.Cart) (int64, error) {
	db := c.mysqlDB.FirstOrCreate(cart, &model.Cart{ProductId: cart.ProductId, SizeId: cart.SizeId, UserId: cart.UserId})
	if db.Error != nil {
		return 0, db.Error
	}
	if db.RowsAffected == 0 {
		return 0, errors.New("", "购物车插入失败", 400)
	}
	return cart.ID, nil
}

func (c *CartRepository) DeleteCartById(cartId int64) error {
	return c.mysqlDB.Where("id = ?", cartId).Delete(&model.Cart{}).Error
}

func (c *CartRepository) UpdateCart(cart *model.Cart) error {
	return c.mysqlDB.Model(&model.Cart{}).Update(cart).Error
}

//根据用户id获取购物车
func (c *CartRepository) FindAll(userId int64) (cartAll []model.Cart, err error) {
	return cartAll, c.mysqlDB.Where("id = ?", userId).Find(&cartAll).Error
}

//根据用户id清空购物车
func (c *CartRepository) ClearCart(userId int64) error {
	return c.mysqlDB.Where("id = ?", userId).Delete(&model.Cart{}).Error
}

//购物车添加商品数量
func (c *CartRepository) IncrNum(cartId int64, num int64) error {
	cart := &model.Cart{ID: cartId}
	return c.mysqlDB.Model(cart).UpdateColumn("num", gorm.Expr("num + ?", num)).Error
}

//购物车减少商品数量
func (c *CartRepository) DecrNum(cartId int64, num int64) error {
	cart := &model.Cart{ID: cartId}
	db := c.mysqlDB.Model(cart).Where("num >= ?", num).UpdateColumn("num", gorm.Expr("num - ?", num))
	if db.Error != nil {
		return db.Error
	}
	if db.RowsAffected == 0 {
		return errors.New("", "减少失败", 400)
	}
	return nil
}
